import type { ToolCallResult } from "@shared/types/openai";
import { useEffect, useState } from "react";

interface ToolCallEventData {
  threadId: string;
  messageId: string;
  toolCallId: string;
  toolName: string;
  result?: string;
  error?: string;
  executionTime?: number;
  toolArguments?: string;
  mcpServerId?: string;
  reason?: string;
}

export function useToolCallUpdates(
  messageId: string,
  initialToolCalls?: string,
) {
  const [toolCalls, setToolCalls] = useState<ToolCallResult[]>(() => {
    if (!initialToolCalls) return [];
    try {
      return JSON.parse(initialToolCalls);
    } catch {
      return [];
    }
  });

  useEffect(() => {
    // Listen for tool call events through window events or other mechanism
    // Since we don't have access to the IPC event system directly in hooks,
    // we'll rely on the database updates and periodic refreshing

    // For now, this is a placeholder for event listening
    // In a real implementation, this would connect to the event system
    const handleToolCallStart = (event: CustomEvent<ToolCallEventData>) => {
      const data = event.detail;
      if (data.messageId !== messageId) return;

      setToolCalls((prev) => {
        const existing = prev.find((tc) => tc.id === data.toolCallId);
        if (existing) {
          return prev.map((tc) =>
            tc.id === data.toolCallId
              ? { ...tc, status: "pending" as const }
              : tc,
          );
        }

        // Add new tool call
        return [
          ...prev,
          {
            id: data.toolCallId,
            name: data.toolName,
            arguments: "", // Will be filled by the actual call
            status: "pending" as const,
          },
        ];
      });
    };

    const handleToolCallSuccess = (event: CustomEvent<ToolCallEventData>) => {
      const data = event.detail;
      if (data.messageId !== messageId) return;

      setToolCalls((prev) =>
        prev.map((tc) =>
          tc.id === data.toolCallId
            ? {
                ...tc,
                status: "success" as const,
                result: data.result,
                executionTime: data.executionTime,
              }
            : tc,
        ),
      );
    };

    const handleToolCallError = (event: CustomEvent<ToolCallEventData>) => {
      const data = event.detail;
      if (data.messageId !== messageId) return;

      setToolCalls((prev) =>
        prev.map((tc) =>
          tc.id === data.toolCallId
            ? {
                ...tc,
                status: "error" as const,
                error: data.error,
              }
            : tc,
        ),
      );
    };

    const handleToolCallApprovalRequired = (
      event: CustomEvent<ToolCallEventData>,
    ) => {
      const data = event.detail;
      if (data.messageId !== messageId) return;

      setToolCalls((prev) =>
        prev.map((tc) =>
          tc.id === data.toolCallId
            ? {
                ...tc,
                status: "awaiting_approval" as const,
                requiresApproval: true,
                mcpServerId: data.mcpServerId,
              }
            : tc,
        ),
      );
    };

    const handleToolCallApproved = (event: CustomEvent<ToolCallEventData>) => {
      const data = event.detail;
      if (data.messageId !== messageId) return;

      setToolCalls((prev) =>
        prev.map((tc) =>
          tc.id === data.toolCallId
            ? {
                ...tc,
                status: "pending" as const, // Back to pending after approval
              }
            : tc,
        ),
      );
    };

    const handleToolCallRejected = (event: CustomEvent<ToolCallEventData>) => {
      const data = event.detail;
      if (data.messageId !== messageId) return;

      setToolCalls((prev) =>
        prev.map((tc) =>
          tc.id === data.toolCallId
            ? {
                ...tc,
                status: "error" as const,
                error: `Tool execution rejected by user${data.reason ? `: ${data.reason}` : ""}`,
                userMessage: data.reason,
              }
            : tc,
        ),
      );
    };

    // Add event listeners to window for custom events
    window.addEventListener(
      "tool-call:start",
      handleToolCallStart as EventListener,
    );
    window.addEventListener(
      "tool-call:success",
      handleToolCallSuccess as EventListener,
    );
    window.addEventListener(
      "tool-call:error",
      handleToolCallError as EventListener,
    );
    window.addEventListener(
      "tool-call:approval-required",
      handleToolCallApprovalRequired as EventListener,
    );
    window.addEventListener(
      "tool-call:approved",
      handleToolCallApproved as EventListener,
    );
    window.addEventListener(
      "tool-call:rejected",
      handleToolCallRejected as EventListener,
    );

    return () => {
      // Clean up event listeners
      window.removeEventListener(
        "tool-call:start",
        handleToolCallStart as EventListener,
      );
      window.removeEventListener(
        "tool-call:success",
        handleToolCallSuccess as EventListener,
      );
      window.removeEventListener(
        "tool-call:error",
        handleToolCallError as EventListener,
      );
      window.removeEventListener(
        "tool-call:approval-required",
        handleToolCallApprovalRequired as EventListener,
      );
      window.removeEventListener(
        "tool-call:approved",
        handleToolCallApproved as EventListener,
      );
      window.removeEventListener(
        "tool-call:rejected",
        handleToolCallRejected as EventListener,
      );
    };
  }, [messageId]);

  // Update tool calls when initialToolCalls changes
  useEffect(() => {
    if (!initialToolCalls) return;
    try {
      const parsed = JSON.parse(initialToolCalls);
      setToolCalls(parsed);
    } catch {
      // Ignore parse errors
    }
  }, [initialToolCalls]);

  return toolCalls;
}
